package test.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author cuichao
 * @Description: NettyServer
 * @Date: create in 2020/12/21 14:36
 */
public class NettyServer {


    public static void main(String[] args) {

        EventLoopGroup master = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();

        ServerBootstrap server = new ServerBootstrap();

        ServerChannel channel = new ServerChannel();

        ChannelInitializer<NioSocketChannel> initializer = new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ServerDecode());
                ch.pipeline().addLast(new ServerEncode());
                ch.pipeline().addLast(channel);
            }
        };

        server
                .group(master,worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 26144)
                .childHandler(initializer)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childOption(ChannelOption.TCP_NODELAY,true);
        try {
            ChannelFuture sync = server.bind(7777).sync();
            System.out.println("Netty-Server is start");
            sync.addListener(f -> {
                if(f.isSuccess()){
                    System.out.println("Netty-Server was started");
                }else{
                    System.err.println(f.cause());
                }
            });
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            master.shutdownGracefully();
            worker.shutdownGracefully();
        }


    }

}
